#!/usr/bin/env python
#coding=utf-8

import MultipartPostHandler
import urllib2
import cookielib
import os
import json
import config
import httplib2
import time
import re
from urllib import urlencode

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Cookie = '115_lang=zh; ssov_2313613=1_2313613_368eef6a640ce8b1c4be31eca16f8728; PHPSESSID=5g9mtl8hmani4h8nequno02497; PAY_PREFERER=my; OOFL=13125185326; ssoidA1=de50ccf7a7d85161130c2057b0178230a718dd3d; ssoinfoA1=2313613%3AA1%3A2876313671; OORA=cc5cda04664c927c6c6db356d139469a322aa5a7; OOFA=%2507%2504PUPS%2502%250CNXW%250DY%250DYY%255D%2502TW%2508%2506%2505T%2501%2525%250F%250A%2501%2508TV%251B%2506PSH%2501%255E%255B%250D%2506%250BZ%2506%255B%2500%250A%2500%2500T%255E%2503%2504%2509%255DTTWSVS%2500%250B%2506QYS%2503%2501%2505PV%2503ZZ%2505TWT%2504%250F_T%250E%2503U; OOFV=444f78e58c394e6949f6ee4c11692694f13d84245bbfe8aea6e28c78fae7ef7be986aba8fbb87440cf0a01b4b21646b4'
BT_API_URL = 'http://btapi.115.com'
BASE_URL = 'http://115.com'

h = httplib2.Http()

header = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'),
          ('Accept', 'application/json, text/javascript, */*; q=0.01'),
          ('Cookie', Cookie),
          ('X-Requested-With','XMLHttpRequest')]

def printf(str):
    print str.decode('UTF-8').encode('GBK')

class DL115(object):

    def __init__(self):
        self.sign = None
        self.time = None
        self.uid = None
        self.cookies = cookielib.CookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
        self.opener.addheaders = header

        self.get_uid()
        self.get_sign()

    def get_torrent_id(self, baidu_source_url):
        #通过百度离线的source_url得到oid
        get_url = config.MY_DATAQUERY_URL + '&type=get_torrent_id&baidu_source_url=' + baidu_source_url
        head, ret = h.request(get_url)
        print ret
        return int(ret)

    def get_uid(self):
        '''
             获取uid
        '''
        ret = self.opener.open(BASE_URL).read()
        reg = re.compile('USER_ID = \'(\d+)')
        ids = re.findall(reg, ret)
        if len(ids) == 0:
            printf('获取uid失败')
            return 1
        self.uid = str(ids[0])
        return 0

    def upload_torrent(self, torrent_oid):
        '''
            path:种子本地路径;
            torrent_oid:原种子id;
            sign:从115页面获取;
            uid:从115页面获取'
        '''
        self.get_sign()

        post_url = BT_API_URL +  '/task/torrent'
        torrent_name = torrent_oid + '.torrent'
        cookies = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies), MultipartPostHandler.MultipartPostHandler)
        params = { 'Filename' : torrent_name, 'time' : self.time, 'sign' : self.sign, 'uid' : self.uid, 'torrent' : open(config.TORRENT_DIR + torrent_name, 'rb'), 'Upload' : 'Submit Query'}
        opener.addheaders = [('User-Agent', 'Shockwave Flash'),
                       ('Accept', 'text/*'),
                       ('Cookie', Cookie)]
        ret = json.loads(opener.open(post_url, params, timeout = 60).read())
        if ret.has_key('error_msg'):
            printf('种子文件上传失败:' +  ret['error_msg'])
            return 1
        if not ret.has_key('file_count') or ret['file_count'] == 0:
            printf( '种子文件为空')
            return 2

        #开始任务
        post_url = BT_API_URL +  '/task/start'
        wanted = '0'
        for i in range(1, ret['file_count']):
            wanted = wanted + '%2C' + str(i)
        m = {'savepath' : ret['torrent_name']}
        s = urlencode(m)
        post_data = 'info_hash=' + ret['info_hash'] + '&wanted=' + wanted + '&' + s + '&uid=' + self.uid + '&sign=' + self.sign + '&time=' + self.time
        ret = json.loads(self.opener.open(post_url, post_data).read())
        if ret.has_key('error_msg'):
            printf('任务开始失败' + ret['error_msg'])
            return 1

        #完成添加操作,将ret['info_hash'] ret['name']更新入数据库
        m = {'torrent_info_hash' : ret['info_hash'], 'torrent_name' : ret['name']}
        s = urlencode(m)
        get_url = config.MY_DATAQUERY_URL + '&type=update_info_hash&' + s + '&ori_torrent_id=' + torrent_oid + "&"
        h.request(get_url)
        return 0

    def get_sign(self):
        '''
        {
            "state": true,
            "data": 12710237830309,
            "size": "11.56TB",
            "url": "http://119.147.156.240/api/file.php",
            "bt_url": "http://119.147.156.240/api/torrent.php",
            "limit": 53687091200,
            "sign": "30967b576400a8f024beb72b991b1515",
            "time": 1380984474
        }
        '''
        get_url = BASE_URL + '/?ct=offline&ac=space&_=' + str(time.time())
        ret = json.loads(self.opener.open(get_url).read())
        if ret.has_key('error_msg'):
            printf('获取sign失败')
            return 1
        self.sign = str(ret['sign'])
        self.time = str(ret['time'])
        return 0

    def get_offline_task_list(self):
        get_url = BASE_URL + '/?ct=offline&ac=list_task&_=' + str(time.time())
        ret = json.loads(self.opener.open(get_url).read())
        return 0

    def get_bt_task_list(self):
        '''
        "status": -2完成
        "status": 4,正在找资源
        "percentDone": 7.57,完成率
        {
    {
        "show": "all",
        "torrents": [
            {
                "info_hash": "2810f36ee5c62fb96d0aa606bcb51758b9ddd244",
                "add_time": 1380994493,
                "percentDone": 100,
                "size": 226228065,
                "peers": 0,
                "rateDownload": 0,
                "torrent_name": "[KTXP][Mushi_Bugyou][26][720P][BIG5].mp4",
                "last_update": 1380898960,
                "status": -2,
                "move": 1,
                "file_id": "91823621349291204",下载完成后
                "left_time": 0
            },
            {
                "info_hash": "0b77985699f34fa2dacfa6ce0662fe0624c4fb14",
        '''
        post_url = BT_API_URL +  '/task/list'

        torrents = []
        post_data = 'page=1&uid=' + self.uid + '&sign=' + self.sign + '&time=' + self.time
        ret1 = json.loads(self.opener.open(post_url, post_data).read())
        if ret1.has_key('torrents'):
            torrents.extend(ret1['torrents'])
            #test
            if ret1['page_count'] > 1:
                post_data = 'page=2&uid=' + self.uid + '&sign=' + self.sign + '&time=' + self.time
                ret2 = json.loads(self.opener.open(post_url, post_data).read())
                torrents.extend(ret2['torrents'])
        return torrents

    def get_bt_task_count(self):
        count = 0
        torrents = self.get_bt_task_list()
        total_rateDownload = 0
        for i in range(0, len(torrents)):
            if torrents[i]['status'] == -1:
                continue
            if torrents[i]['file_id'] == None:
                count = count + 1
                printf('任务:%100s  进度:%8s  速度:%10dKB/s  种子:%5s  体积: %5.2f    散列值:%40s' % (torrents[i]['torrent_name'], str(torrents[i]['percentDone']), torrents[i]['rateDownload']/1024.0, str(torrents[i]['peers']), torrents[i]['size']/1024.0/1024.0/1024.0, str(torrents[i]['info_hash'])))
                total_rateDownload += torrents[i]['rateDownload']/1024.0
        printf('---------------------------------总速度:%5.2f MB/s' % (total_rateDownload/1024.0))
        return count

    def auto_make_share_link(self):
     #自动将完成任务生成网盘礼包
        torrents = self.get_bt_task_list()
        for i in range(0, len(torrents)):
            if torrents[i]['status'] == -1:
                post_url = BT_API_URL + '/task/del'
                post_data = 'hash%5B0%5D=' + torrents[i]['info_hash'] + '&uid=' + self.uid + '&sign=' + self.sign + '&time=' + self.time
                self.opener.open(post_url, post_data)
                continue
            if torrents[i]['file_id'] != None and (torrents[i]['status'] == -2 or (torrents[i]['status'] == 0 and torrents[i]['percentDone'] == 100)):
                try:
                    cid = str(torrents[i]['file_id'])
                    torrent_name = '%s' % torrents[i]['torrent_name']
                    get_url = 'http://web.api.115.com/category/get?aid=1&cid=' + cid
                    ret = self.opener.open(get_url).read()#sometime has bom
                    if ret.find('pick_code') < 0:
                        printf('暂时还无法分享')#此时无bom
                        continue
                    ret = ret[3:]
                    printf(ret)
                    ret = json.loads(ret)
                    pick_code = ret['pick_code']
                    #创建礼包
                    post_url = BASE_URL + '/?ct=filegift&ac=create'
                    post_data = 'pickcodes%5B%5D=' + pick_code
                    ret = json.loads(self.opener.open(post_url, post_data).read())
                    gift_code = ret['gift_code']
                    #保存礼包名字
                    post_url = BASE_URL + '/?ct=filegift&ac=update_remark'
                    m = {'remark' : torrent_name}
                    s = urlencode(m)
                    post_data = 'gift_code=' + gift_code + '&' + s
                    ret = json.loads(self.opener.open(post_url, post_data).read())
                    #将gift_code更新入数据库中
                    get_url = config.MY_DATAQUERY_URL + '&type=update_gift_code' + '&gift_code=' + gift_code + '&torrent_info_hash=' + torrents[i]['info_hash']
                    head, ret = h.request(get_url)
                    if ret == '0':
                        #115从完成列表中删除
                        post_url = BT_API_URL + '/task/del'
                        post_data = 'hash%5B0%5D=' + torrents[i]['info_hash'] + '&uid=' + self.uid + '&sign=' + self.sign + '&time=' + self.time
                        self.opener.open(post_url, post_data)
                except Exception,ex:
                    printf(Exception,":",ex)


    def make_share_link(self, torrent_info_hash):
        #生成网盘礼包
        torrents = self.get_bt_task_list()
        for i in range(0, len(torrents)):
            if torrents[i]['info_hash'] == torrent_info_hash:
                cid = str(torrents[i]['file_id'])
                torrent_name = '%s' % torrents[i]['torrent_name']
                get_url = 'http://web.api.115.com/category/get?aid=1&cid=' + cid
                ret = json.loads(self.opener.open(get_url).read()[3:])#BOM
                pick_code = ret['pick_code']
                #创建礼包
                post_url = BASE_URL + '/?ct=filegift&ac=create'
                post_data = 'pickcodes%5B%5D=' + pick_code
                ret = json.loads(self.opener.open(post_url, post_data).read())
                gift_code = ret['gift_code']
                #保存礼包名字
                post_url = BASE_URL + '/?ct=filegift&ac=update_remark'
                m = {'remark' : torrent_name}
                s = urlencode(m)
                post_data = 'gift_code=' + gift_code + '&' + s
                ret = json.loads(self.opener.open(post_url, post_data).read())
                #将gift_code更新入数据库中
                get_url = config.MY_DATAQUERY_URL + '&type=update_gift_code' + '&gift_code=' + gift_code + '&torrent_info_hash=' + torrent_info_hash
                head, ret = h.request(get_url)
                if ret == '0':
                    #115从完成列表中删除
                    post_url = BT_API_URL + '/task/del'
                    post_data = 'hash%5B0%5D=' + torrent_info_hash + '&uid=' + self.uid + '&sign=' + self.sign + '&time=' + self.time
                    self.opener.open(post_url, post_data)
                return 0
        return 1